<!--
	作者：offline
	时间：2018-08-11
	描述：供应商主数据
-->
<template>
  <div class="m-view-supplierManager m-window" v-loading="btnLoading">
    <div class="m-condition" v-if="show1">
      <el-row :gutter="5">
        <el-col :span="4">
          <!-- <el-form-item label="分类" class="rightItem"> -->
          <el-select
            v-model="selCategoryCode"
            clearable
            placeholder="请选择供应商分类"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <!-- </el-form-item> -->
        </el-col>
        <el-col :span="4">
          <!-- <el-form-item label="编号/名称" class="rightItem"> -->
          <el-input
            v-model="name"
            clearable
            @keyup.enter.native="search(1)"
            placeholder="供应商编号或名称"
          ></el-input>
          <!-- </el-form-item> -->
        </el-col>
        <el-col :span="2">
          <el-checkbox v-model="state" @change="changeState"
            >显示停用</el-checkbox
          >
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="search(1)">查询</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="edit('view')">查看</el-button>
        </el-col>
        <el-col :span="2">
          <el-button
            type="primary"
            @click="showSupplierDialog"
            :disabled="btnDisabled"
            >引入</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button
            type="primary"
            @click="edit('edit')"
            :disabled="btnDisabled"
            >编辑</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button
            type="primary"
            @click="active"
            :disabled="btnDisabled || !isActive"
            >激活主账号</el-button
          >
        </el-col>
        <el-col :span="2" v-if="true">
          <el-button
            type="primary"
            @click="updateSap"
            :disabled="btnDisabled"
            :loading="synchro"
            >同步</el-button
          >
        </el-col>
        <el-col :span="2" v-if="delShow">
          <el-button type="primary" @click="del">停用</el-button>
        </el-col>
        <el-col :span="2" v-if="reuseShow">
          <el-button type="primary" @click="reuse">启用</el-button>
        </el-col>
        <el-col :span="4" v-if="ccAuth" class="m-floatRight mt-10">
          <el-button
            type="primary"
            @click="permitCcAuth"
            :disabled="ccAuthBtnDisabled"
            >更新CC沟通权限</el-button
          >
        </el-col>
      </el-row>
    </div>
    <div :class="['m-agTable m-bottom', { 'g-top100': ccAuth }]" v-if="show1">
      <ag-grid-vue
        class="m-agTableContent ag-theme-balham"
        :gridOptions="gridOptions"
        :columnDefs="columnDefs"
        :rowData="rowData"
        v-loading="loading"
        rowSelection="multiple"
      ></ag-grid-vue>
    </div>
    <div class="m-page" v-if="show1">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        @prev-click="handlePrevClick"
        @next-click="handleNextClick"
        :current-page="currentPage"
        :page-sizes="[30, 50, 100, 150, 200]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <div class="m-condition" v-if="show2">
      <el-row :gutter="15">
        <el-col :span="12" :offset="10" style="font-size:18px">
          {{ fontTitle }}
        </el-col>
      </el-row>
      <!-- <div class="m-pageHeader">
        <div class="m-headerItem">
          编号:
          <span>{{selSupplierCode}}</span>
        </div>
        <div class="m-headerItem">
          名称:
          <span :title="selSupplierName">{{selSupplierName}}</span>
        </div>
        <div class="m-headerItem">
          供应商分类:
          <span>{{selCategoryDesc}}</span>
        </div>
      </div>
      <el-row>
        <el-col :span="18">地址: {{selSupplierAddress}}</el-col>
			</el-row>-->
      <el-tabs
        v-model="activeName"
        :class="isOk ? 'tab-condition' : 'tab-condition2'"
        type="border-card"
      >
        <el-tab-pane
          v-for="item in editableTabs"
          :label="item.title"
          :name="item.name"
          :key="item.name"
        >
          <component
            :is="item.content"
            ref="c1"
            @setRuleFormData="getRuleFormData"
            :sapSupplierInfo="setSelectedSapSupplierInfo"
            :tableData="item.tableData"
            :mode="mode"
          ></component>
        </el-tab-pane>
      </el-tabs>
      <el-row :gutter="10" class="btn-condition">
        <el-col :span="2" :offset="10">
          <el-button @click="cancel">{{
            mode == "view" ? "返回" : "取消"
          }}</el-button>
        </el-col>
        <el-col :span="2" v-if="mode != 'view'">
          <el-button type="primary" @click="saveData">保存</el-button>
        </el-col>
      </el-row>
    </div>

    <!--弹框-->
    <el-dialog
      :title="title"
      v-if="dialogVisible"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
      v-dialogDrag
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        :rules="rules"
      >
        <el-form-item label="供应商" prop="supplierCode">
          <el-input
            v-model="ruleForm.supplierCode"
            placeholder="请选择供应商"
            clearable
            :readonly="inputDis"
            @focus="showSupplierDialog"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              v-if="btnShow"
              @click="showSupplierDialog"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="公司" prop="companyCode" v-if="itemShow">
          <el-input
            v-model="companyCode"
            placeholder="请选择公司"
            clearable
            :readonly="inputDis"
            @focus="showCompanyDialog"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="showCompanyDialog"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="采购组织" v-if="itemShow">
          <el-select
            v-model="selPurOrgCode"
            placeholder="请选择采购组织"
            clearable
            @change="getPurOrgInfo"
          >
            <el-option
              v-for="item in purOrgOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商分类" v-if="itemShow">
          <el-select
            v-model="selCategoryCode2"
            placeholder="请选择供应商"
            :disabled="inputDis"
          >
            <el-option
              v-for="item in categoryOptions2"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog" :disabled.sync="disState"
          >取消</el-button
        >
        <el-button type="primary" @click="nextStep" :disabled.sync="disState"
          >下一步</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="SAP供应商信息"
      v-if="supplierDialogVisible"
      :visible.sync="supplierDialogVisible"
      width="65%"
      :before-close="supplierDialogClose"
      v-dialogDrag
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="dialogLoading"
    >
      <sapSupplierInfo
        ref="sapSupplierInfo"
        @setSapSupplierInfo="getSelectedSupplier"
        :showIsSelected="isShowSelected"
        @dataLoading="dataLoaded"
      ></sapSupplierInfo>
    </el-dialog>

    <!-- <el-dialog title="公司选择" :visible.sync="srmCompanyDialogVisible" width="50%" :before-close="srmCompanyDialogClose" v-dialogDrag :close-on-click-modal="false" :close-on-press-escape="false">
			<srmCompanyInfo ref="srmCompanyInfo" @setSrmCompanyInfo="getSelectedCompany"></srmCompanyInfo>
		</el-dialog>-->

    <el-dialog
      title="SAP公司信息"
      v-if="srmCompanyDialogVisible"
      :visible.sync="srmCompanyDialogVisible"
      width="50%"
      :before-close="srmCompanyDialogClose"
      v-dialogDrag
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <supplierSapInfo
        ref="supplierSapInfo"
        @setSapSupplierCompanyInfo="getSelectedCompany"
        :setSelectedSupplierCode="getSelectedSupplierCode"
      ></supplierSapInfo>
    </el-dialog>
  </div>
</template>

<script>
import _Api from "@/api";
import localeText from "@/i18n/agGridText";
import { categoryCode, purOrgCode } from "@/public/enum";
import sapSupplierInfo from "@/components/sapSupplierInfo";
import srmCompanyInfo from "@/components/srmCompanyInfo";
import baseInfo from "@/views/masterData/baseInfo";
import companyInfo from "./common/companyView";
import purchaseInfo from "./common/purchaseView";
import supplierSapInfo from "@/components/supplierSapInfo";
import Msg from "@/public/message";
import gridOptions from "lesso-common/public/gridOptions";
import constant from "@/public/constant";

//import { showAlert } from 'lesso-common/public/utils'

export default {
  data() {
    return {
      info: "",
      columnDefs: [],
      rowData: [],
      currentPage: 1,
      pageSize: 30,
      total: 0,
      loading: false,
      show1: true,
      show2: false,
      selCategoryCode: "",
      categoryOptions: [],
      delShow: true,
      reuseShow: false,
      ccAuth: false,
      ccAuthBtnDisabled: false,
      btnDisabled: false,
      name: "",
      state: false,
      title: "供应商维护",
      dialogVisible: false,
      inputDis: true,
      ruleForm: {},
      btnShow: true,
      rules: {
        supplierCode: [
          {
            required: true,
            trigger: "change",
            message: "请选择供应商编号"
          }
        ]
      },
      selPurOrgCode: "",
      selCategoryCode2: "",
      selCategoryDesc: "",
      purOrgOptions: [],
      categoryOptions2: [],
      disState: false,
      mode: "",
      supplierDialogVisible: false,
      srmCompanyDialogVisible: false,
      selSupplierCode: "",
      selSupplierName: "",
      selCompanyCode: "",
      selCompanyName: "",
      selSupplierAddress: "",
      itemShow: false,
      companyCode: "",
      comShow: false,
      purShow: false,
      editableTabs: [
        {
          name: "基本信息",
          content: baseInfo,
          title: "基本信息",
          hidden: false,
          tableData: []
        },
        {
          name: "公司信息",
          content: companyInfo,
          title: "公司信息",
          hidden: false,
          tableData: []
        },
        {
          name: "采购信息",
          content: purchaseInfo,
          title: "采购信息",
          hidden: false,
          tableData: []
        }
      ],
      activeName: "基本信息",
      selCountry: "", //获取sap供应商组件里所选的国家
      selAddress: "", //获取sap供应商组件里所选的地址
      selArea: "", //获取sap供应商组件里所选的地区
      setSelectedSapSupplierInfo: {},
      fontTitle: "",
      getSelectedSupplierCode: "",
      account: "",
      selPurOrgDesc: "",
      isOk: true,
      sapInfo: {},
      isShowSelected: true,
      mainAccount: "",
      current: 1,
      dialogLoading: false,
      // 按钮异步加载中
      btnLoading: false,
      // 供应商信息数据加载
      infoLoading: false,
      //激活按钮可编辑状态
      isActive: true,
      synchro: false
    };
  },
  props: ["sapSupplierInfo", "srmCompanyInfo", "setSelectedSupplierCode"],
  created() {},
  beforeMount() {
    this.gridOptions = Object.assign(
      {
        context: {
          componentParent: this
        },
        rowSelection: "multiple",
        enableColResize: true,
        localeText: localeText,
        suppressRowClickSelection: true,
        onRowSelected: gird => {
          let rows = gird.api.getSelectedRows();
          this.isActive = rows.some(item => {
            return item.mainAccount == "";
          });
        }
        //   getContextMenuItems: this.getContextMenuItems
      },
      gridOptions()
    );
    this.columnDefs = [
      {
        headerName: "编号",
        field: "supplierCode",
        checkboxSelection: true,
        headerCheckboxSelection: true,
        headerCheckboxSelectionFilteredOnly: true
      },
      { headerName: "主账号", field: "mainAccount" },
      {
        headerName: "名称",
        field: "supplierName",
        tooltipField: "supplierName"
      },
      {
        headerName: "供应商分类",
        field: "categoryCode",
        cellRenderer: function(params) {
          for (var i = 0; i < categoryCode.length; i++) {
            if (params.value == categoryCode[i].value) {
              return categoryCode[i].label;
            }
          }
        }
      },
      { headerName: "地址", field: "address", tooltipField: "address" }, //,cellRenderer:function(params){return '<a href="" style="color:blue">'+params.value+'</a>'}
      {
        headerName: "电子签账号",
        field: "eSignAccount",
        tooltipField: "eSignAccount"
      },
      {
        headerName: "电子签状态",
        field: "isESign",
        cellRenderer: params => {
          if (params.value !== "") {
            if (params.value == 2) {
              return "认证通过";
            } else if (params.value == 1) {
              return "认证中";
            } else if (params.value == 0) {
              return "未认证";
            }
          }
        }
      },
      {
        headerName: "状态",
        field: "state",
        cellRenderer: function(params) {
          if (params.value == "1") return '<span class="ag-icon">停用</span>';
          else if (params.value == "0")
            return '<span  class="ag-icon">启用</span>';
        }
      }
    ];
    this.categoryOptions = categoryCode;
  },
  methods: {
    // 开通cc沟通授权
    permitCcAuth() {
      let row = this.gridOptions.api.getSelectedRows();
      if (row.length <= 0) {
        Msg.showPopMsg("提示：请选择记录");
        return;
      } else if (row.length > 10) {
        Msg.showPopMsg("提示：每次最多只能选择10条记录，请重新选择！");
        return;
      }
	  this.ccAuthBtnDisabled = true;
	  let suppliers = [];
	  for(let {mainAccount} of row) {
		  suppliers.push(mainAccount)
	  }
      _Api
        .grantCommunicationAuth(suppliers)
        .then(({data:{code, info}}) => {
		  this.ccAuthBtnDisabled = false;
          if (code == "1") {
            Msg.showSuccessMsg("授权成功");
          } else {
            Msg.showErrorMsg(info);
          }
        })
        .catch(err => {
		  this.ccAuthBtnDisabled = false;
          Msg.showErrorMsg(err.message);
        });
    },
    dataLoaded(val) {
      this.dialogLoading = val;
    },
    updateSap() {
      var row = this.gridOptions.api.getSelectedRows();
      var that = this;
      if (row.length <= 0) {
        Msg.showPopMsg("提示：请选择需要同步的记录");
        return;
      } else if (row.length > 15) {
        Msg.showPopMsg("提示：每次最多只能同步15条记录，请重新选择！");
        return;
      }
      this.$confirm("是否确认同步选中的记录？", "消息提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        distinguishCancelAndClose: true
      })
        .then(() => {
          let obj = {};
          let arr = [];
          for (let i in row) {
            obj.supplierCode = row[i].supplierCode;
            obj.modifyer = this.$global.user.employeeName;
            obj.modifyerId = this.$global.user.id;
            arr.push(obj);
          }
          this.synchro = true;
          _Api
            .syncSupplierToSap(arr)
            .then(function(response) {
              let data = response.data;
              that.synchro = false;
              if (data.code == "1") {
                Msg.showSuccessMsg("操作成功");
                that.search();
              } else {
                Msg.showErrorMsg(data.info);
              }
            })
            .catch(err => {
              this.synchro = false;
              Msg.showErrorMsg(err.message);
            });
        })
        .catch(() => {});
    },
    getContextMenuItems() {
      return [];
    },
    getBtnAuth() {
      let obj = {
        resultType: "0",
        code: "supplierManager",
        authClientCode: constant.authCode.code,
        authTenantCode: constant.authCode.tcode
      };
      _Api
        .getUserAuthMenu(obj)
        .then(response => {
          var data = response.data;
          if (data.code == "1") {
            if (data.total > 0) {
              for (let i in data.rows) {
                if (data.rows[i].code == "ccAuth") {
                  this.ccAuth = true;
                }
              }
            }
          }
        })
        .catch(err => {
          Msg.showErrorMsg(err.data.message);
        });
    },
    saveData() {
      this.getRuleFormData(
        this.$refs.c1[0].ruleForm,
        this.$refs.c1[1].tableData
      );
      // if (this.activeName == "基本信息") {
      // 	this.$refs.c1[0].getValidator();
      // } else if (this.activeName == "公司信息") {
      // 	this.$refs.c1[1].getValidator();
      // }
    },
    //查询按钮事件
    // search(){
    // 	this.search("");
    // },
    //flag = 1 表示查询第一页； 否则查询当前页
    search(flag) {
      var s;
      if (this.state == false) s = 0;
      else s = 1;
      var obj = {
        state: s,
        current: this.current,
        size: this.pageSize
      };
      this.name = this.name.replace(/\s+/g, "");
      if (this.name) obj.name = this.name;
      if (this.selCategoryCode) obj.categoryCode = this.selCategoryCode;
      if (flag == 1) this.currentPage = 1;
      obj.size = this.pageSize;
      obj.current = this.currentPage;
      obj.activeFlag = 1;
      var that = this;
      this.loading = true;
      _Api
        .getSupplierInfo(obj)
        .then(function(response) {
          var data = response.data;
          if (data.code == "1") {
            if (data.total > 0) {
              that.gridOptions.api.setRowData(data.rows.splice(0));
              that.total = data.total;
              // that.gridOptions.api.sizeColumnsToFit();
              //							let allColumnIds = [];
              //							that.gridOptions.columnApi.getAllColumns().forEach(function(column) {
              //								allColumnIds.push(column.colId);
              //							});
              //							that.gridOptions.columnApi.autoSizeColumns(allColumnIds);
            } else {
              that.gridOptions.api.setRowData([]);
              that.total = 0;
            }
          } else {
            Msg.showErrorMsg(data.info);
          }
          that.loading = false;
        })
        .catch(err => {
          Msg.showErrorMsg(err.data.message);
          that.loading = false;
        });
    },
    add() {
      this.title = "供应商引入";
      this.dialogVisible = true;
      this.categoryOptions2 = categoryCode;
      var that = this;
      this.$nextTick(_ => {
        that.$refs.ruleForm.clearValidate();
      });
      this.mode = "add";
      this.$set(this.ruleForm, "supplierCode", "");
      this.companyCode = "";
      this.purOrgOptions = [];
      this.selPurOrgCode = "";
      this.btnShow = true;
      this.fontTitle = "供应商引入";
    },
    edit(type) {
      var row = this.gridOptions.api.getSelectedRows();
      if (type == "edit") {
        if (row.length <= 0) {
          Msg.showPopMsg("提示：请选择需要编辑的记录");
          return;
        }
        if (row.length > 1) {
          Msg.showPopMsg("提示：只能选择单条记录进行编辑操作！");
          return;
        }
      } else if (type == "view") {
        if (row.length <= 0) {
          Msg.showPopMsg("提示：请选择需要查看的记录");
          return;
        }
        if (row.length > 1) {
          Msg.showPopMsg("提示：只能选择单条记录进行查看操作！");
          return;
        }
      }
      this.selSupplierCode = row[0].supplierCode;
      this.selSupplierName = row[0].supplierName;
      this.selSupplierAddress = row[0].address;
      this.getCompanyList(row[0].id);
      this.getSelectedCategoryDesc(row[0].categoryCode);
      this.mode = type;
      this.setSelectedSapSupplierInfo = row[0];
      this.fontTitle = type == "edit" ? "供应商编辑" : "供应商查看";
      this.getSapPurOrgBySupplierCode(this.selSupplierCode);
      this.dialogVisible = false;
      this.$set(
        this.ruleForm,
        "supplierCode",
        row[0].supplierName + "  (" + row[0].supplierCode + ")"
      );
      this.getSelectedSupplierCode = row[0].supplierCode;
      this.btnShow = false;
      //   this.nextStep();
    },

    del() {
      var row = this.gridOptions.api.getSelectedRows();
      if (row.length <= 0) {
        Msg.showPopMsg("提示：请选择需要停用的记录");
        return;
      }
      var that = this;
      this.$confirm("是否确认停用该记录？", "消息提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        distinguishCancelAndClose: true
      })
        .then(() => {
          var id = "";
          for (var i = 0; i < row.length; i++) {
            id += row[i].id + ",";
          }
          id = id.substr(0, id.length - 1);
          var obj = {
            id: id,
            state: 1,
            modifyer: this.$global.user.loginName,
            modifyerId: this.$global.user.id
          };
          _Api
            .delSupplierInfo(obj)
            .then(function(response) {
              var data = response.data;
              if (data.code == "1") {
                Msg.showSuccessMsg("操作成功");
              } else {
                Msg.showErrorMsg(data.info);
              }
              that.search();
            })
            .catch(err => {
              Msg.showErrorMsg(err.message);
            });
        })
        .catch(() => {});
    },
    reuse() {
      var row = this.gridOptions.api.getSelectedRows();
      if (row.length <= 0) {
        Msg.showPopMsg("提示：请选择需要启用的记录");
        return;
      }
      var that = this;
      this.$confirm("是否确认启用该记录？", "消息提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        distinguishCancelAndClose: true
      })
        .then(() => {
          var id = "";
          for (var i = 0; i < row.length; i++) {
            id += row[i].id + ",";
          }
          id = id.substr(0, id.length - 1);
          var obj = {
            id: id,
            state: 0,
            modifyer: this.$global.user.loginName,
            modifyerId: this.$global.user.id
          };
          _Api
            .delSupplierInfo(obj)
            .then(function(response) {
              var data = response.data;
              if (data.code == "1") {
                Msg.showSuccessMsg("操作成功");
              } else {
                Msg.showErrorMsg(data.info);
              }
              that.search();
            })
            .catch(err => {
              Msg.showErrorMsg(err.message);
            });
        })
        .catch(() => {});
    },
    changeState(params) {
      if (params == true) {
        this.btnDisabled = true;
        this.delShow = false;
        this.reuseShow = true;
      } else {
        this.btnDisabled = false;
        this.delShow = true;
        this.reuseShow = false;
      }
      this.search(1);
    },
    cancel() {
      this.show1 = true;
      this.show2 = false;
      this.companyCode = "";
      this.selPurOrgCode = "";
      this.selCategoryCode2 = "";
      this.selSupplierCode = "";
      this.selSupplierAddress = "";
      this.selSupplierName = "";
      this.selCategoryDesc = "";
      this.setSelectedSapSupplierInfo = {};
      this.mode = "";
      this.selPurOrgDesc = "";
      this.selCompanyName = "";
      this.comShow = false;
      this.purShow = false;
      this.search();
    },
    handleSizeChange(params) {
      this.pageSize = params;
      this.current = 1;
      this.currentPage = 1;
      this.search();
    },
    handleCurrentChange(params) {
      this.current = params;
      this.currentPage = params;
      this.search();
    },
    handlePrevClick(params) {
      this.current = params;
      this.currentPage = params;
      this.search();
    },
    handleNextClick(params) {
      this.current = params;
      this.currentPage = params;
      this.search();
    },
    handleClose(done) {
      this.companyCode = "";
      this.selPurOrgCode = "";
      this.selCategoryCode2 = "";
      this.purOrgOptions = [];
      this.getSelectedSupplierCode = "";
      this.supplierDialogVisible = false;
      done();
      this.search();
    },
    showSupplierDialog() {
      // var that = this;
      this.mode = "add";
      this.fontTitle = "供应商引入";
      if (this.mode == "edit" || this.mode == "view") return;
      this.supplierDialogVisible = true;
      // this.$nextTick(_ => {
      // 	that.$refs.sapSupplierInfo.search();
      // })
    },
    showCompanyDialog() {
      var that = this;
      this.srmCompanyDialogVisible = true;
      this.$nextTick(_ => {
        that.$refs.supplierSapInfo.search();
      });
    },
    nextStep() {
      if (this.mode == "add") {
        // this.$refs["ruleForm"].validate((valid) => {
        // if (!valid) {
        //   return false;
        // } else {
        this.dialogVisible = false;
        this.show1 = false;
        this.show2 = true;
        // }
        // });
        if (this.selPurOrgDesc) {
          this.purShow = true;
        }
        if (this.selCompanyName) {
          this.comShow = true;
        }
        if (this.purShow && this.comShow) {
          this.isOk = false;
        }
      } else if (this.mode == "edit" || this.mode == "view") {
        this.dialogVisible = false;
        this.show1 = false;
        this.show2 = true;
      }
    },
    cancelDialog() {
      this.companyCode = "";
      this.selPurOrgCode = "";
      this.selCategoryCode2 = "";
      this.dialogVisible = false;
      this.mode = "";
      this.getSelectedSupplierCode = "";
      this.purOrgOptions = [];
      //this.search();
    },
    supplierDialogClose(done) {
      done();
    },
    getSelectedSupplier(msg) {
      if (msg[0]) {
        this.supplierDialogVisible = false;
        this.$set(
          this.ruleForm,
          "supplierCode",
          msg[0].supplierName + "  (" + msg[0].supplierCode + ")"
        );
        this.selSupplierCode = msg[0].supplierCode;
        this.selSupplierName = msg[0].supplierName;
        this.selSupplierAddress = msg[0].address;
        this.selCategoryCode2 = msg[0].categoryCode;
        this.getSelectedSupplierCode = msg[0].supplierCode;
        this.getCompanyList(msg[0].id);
        this.getSapPurOrgBySupplierCode(this.getSelectedSupplierCode);
        const {
          address,
          categoryCode,
          isESign,
          supplierCode,
          supplierName
        } = msg[0];
        this.setSelectedSapSupplierInfo = {
          mode: "add",
          selAddress: msg[0].address,
          selCountry: msg[0].country,
          selArea: msg[0].area,
          creditCode: msg[0].creditCode,
          mail: msg[0].mail,
          linkMan: msg[0].linkMan,
          linkNumber: msg[0].linkNumber,
          phone: msg[0].phone,
          fax: msg[0].fax,
          id: msg[0].id,
          address,
          categoryCode,
          isESign,
          supplierCode,
          supplierName
        };
        this.getSelectedCategoryDesc(this.selCategoryCode2);
        // this.nextStep()
        // this.$nextTick(_ => {
        //   that.$refs.ruleForm.clearValidate();
        // });
      }
    },
    // 获取供应商所属公司集合
    getCompanyList(id) {
      this.btnLoading = true;
      this.$http
        .getCompanyView({ supplierId: id })
        .then(({ data }) => {
          if (data.code == 1) {
            this.editableTabs[1].tableData = data.rows;
            this.getPurchaseList(id);
          } else {
            this.btnLoading = false;
            Msg.showErrorMsg(data.info);
          }
        })
        .catch(err => {
          this.btnLoading = false;
          Msg.showErrorMsg(err.data.message);
        });
    },
    // 获取供应商所属采购组织集合
    getPurchaseList(id) {
      this.$http
        .getPurchaseOption({ supplierId: id })
        .then(({ data }) => {
          this.btnLoading = false;
          if (data.code == 1) {
            this.editableTabs[2].tableData = data.rows;
            this.nextStep();
          } else {
            Msg.showErrorMsg(data.info);
          }
        })
        .catch(err => {
          this.btnLoading = false;
          Msg.showErrorMsg(err.data.message);
        });
    },
    getSelectedCategoryDesc(data) {
      if (data) {
        for (var i = 0; i < this.categoryOptions.length; i++) {
          var obj = this.categoryOptions[i];
          if (obj.value == data) {
            this.selCategoryDesc = obj.label;
            return;
          }
        }
      }
    },
    getSelectedCompany(msg) {
      var that = this;
      if (msg[0]) {
        this.srmCompanyDialogVisible = false;
        this.companyCode = msg[0].companyName + " (" + msg[0].companyCode + ")";
        this.selCompanyCode = msg[0].companyCode;
        this.selCompanyName = msg[0].companyName;
        this.$nextTick(_ => {
          that.$refs.ruleForm.clearValidate();
        });
      }
    },
    srmCompanyDialogClose(done) {
      done();
    },
    getRuleFormData(msg, companyInfo) {
      //验证通过后保存方法
      //   if (this.mode == "add") {
      //     this.getSapInfoBySupplierCode(this.selSupplierCode, msg);
      //     this.mode = "";
      //   } else if (this.mode == "edit") {}
      // if (this.activeName == "基本信息") {
      msg.modifyerId = this.$global.user.id;
      msg.modifyer = this.$global.user.loginName;
      msg.activeFlag = 1;
      msg.isESign =
        msg.isESign == "未认证" ? 0 : msg.isESign == "认证中" ? 1 : 2;
      msg.companyList = companyInfo;
      var that = this;
      _Api.modifySupplier(msg).then(function(response) {
        var data = response.data;
        if (data.code == "1") {
          Msg.showSuccessMsg("保存成功");
        } else {
          Msg.showErrorMsg(data.info);
        }
        that.cancel();
        that.search();
      });
      this.mode = "";
      // } else if (this.activeName == "公司信息") {
      // 	this.saveCompanyInfo(msg);
      // }
    },
    // 保存公司视图修改信息
    saveCompanyInfo(rows) {
      _Api
        .saveSupplierCompany(rows)
        .then(({ data }) => {
          if (data.code == 1) {
            Msg.showSuccessMsg("保存成功");
            this.cancel();
            this.search();
          } else {
            Msg.showErrorMsg(data.info);
          }
        })
        .catch(err => {
          Msg.showErrorMsg(err.data.message);
        });
    },
    //激活主账号
    active() {
      var row = this.gridOptions.api.getSelectedRows();
      if (row.length <= 0) {
        Msg.showPopMsg("提示：请选择需要激活的记录");
        return;
      }
      if (row.length > 1) {
        Msg.showPopMsg("提示：只能选择单条记录进行激活操作！");
        return;
      }
      var param = {};
      if (row[0].mail) {
        var reg = new RegExp(
          "^([0-9A-Za-z-_.]+)@([0-9a-z]+.[a-z]{2,3}(.[a-z]{2})?)$"
        );
        if (!reg.test(row[0].mail)) {
          Msg.showPopMsg("邮箱格式不正确，请维护正确格式的邮箱号码！");
          return;
        }
      }
      param.userName = "G" + row[0].supplierCode.replace(/\b(0+)/gi, "");
      param.phone = row[0].phone;
      param.supplierCode = row[0].supplierCode;
      param.supplierName = row[0].supplierName;
      param.email = row[0].mail;
      this.mainAccount = param.userName;
      var obj = {
        status: true,
        mainAccount: this.mainAccount,
        id: row[0].id
      };
      this.btnLoading = true;
      _Api
        .acviteMainAccount(param)
        .then(response => {
          var data = response.data;
          if (data.code == "1") {
            Msg.showSuccessMsg(data.info);
            this.updateMainAccount(obj);
          } else {
            this.btnLoading = false;
            Msg.showErrorMsg(data.info);
          }
        })
        .catch(err => {
          this.btnLoading = false;
          Msg.showErrorMsg(err.data.message);
        });
    },
    // 更新供应商主数据
    updateMainAccount(data) {
      const { status, mainAccount, id } = data;
      if (!status) return;
      var editParam = {
        id: id,
        mainAccount: mainAccount,
        modifyerId: this.$global.user.id,
        modifyer: this.$global.user.loginName
      };
      _Api
        .editSupplierInfo(editParam)
        .then(response => {
          var data = response.data;
          this.btnLoading = false;
          if (data.code == "1") {
            this.search();
          } else {
            Msg.showErrorMsg(data.info);
          }
        })
        .catch(err => {
          this.btnLoading = false;
          Msg.showErrorMsg(err.data.message);
        });
    },

    getSapPurOrgBySupplierCode(supplierCode) {
      if (supplierCode) {
        var obj = {
          name: supplierCode
        };
        var that = this;
        this.purOrgOptions = [];
        _Api.getRalSAPInfoBySupplierCode(obj).then(function(response) {
          var data = response.data;
          if (data.code == "1") {
            if (data.rows.l_SAPOrg.length > 0) {
              console.log(purOrgCode);
              for (var i = 0; i < purOrgCode.length; i++) {
                for (var j = 0; j < data.rows.l_SAPOrg.length; j++) {
                  if (purOrgCode[i].value == data.rows.l_SAPOrg[j].purOrgCode) {
                    that.purOrgOptions.push(purOrgCode[i]);
                  }
                }
              }
            }
          }
        });
      }
    },
    getPurOrgDesc(purCode) {
      console.log("获取采购组织描述");
      for (var i = 0; i < purOrgCode.length; i++) {
        if (purOrgCode[i].value == purCode) {
          this.selPurOrgDesc = purOrgCode[i].label;
          return;
        }
      }
    },
    getPurOrgInfo(params) {
      this.getPurOrgDesc(params);
    },
    visa() {
      var row = this.gridOptions.api.getSelectedRows();
      if (row.length <= 0) {
        Msg.showPopMsg("提示：请选择需要开通电子签的记录");
        return;
      }
      if (row.length > 1) {
        Msg.showPopMsg("提示：只能选择单条记录进行开通电子签操作！");
        return;
      }
      var obj = {
        name: row[0].supplierCode
      };
      // var that = this;
      _Api
        .registerVisa(obj)
        .then(function(response) {
          var data = response.data;
          if (data.Code == "1") {
            Msg.showErrorMsg(data.Error);
          } else if (data.Code == "0") {
            Msg.showSuccessMsg("操作成功");
          }
        })
        .catch(err => {
          Msg.showErrorMsg(err.data.message);
        });
    },
    // addSapInfoBySupplierCode(msg){
    // 	//根据供应商编号保存sap应付人员和采购组织信息
    // 	msg.supplierCode = this.selSupplierCode;
    // 	msg.supplierName = this.selSupplierName;
    // 	msg.categoryCode = this.selCategoryCode2
    // 	msg.creatorId = this.$global.user.id;
    // 	msg.creator = this.$global.user.loginName;
    // 	var that = this;
    // 	_Api.addSupplierInfo(msg).then(function(response){
    // 		var data = response.data;
    // 		if(data.code == "1"){
    // 			Msg.showSuccessMsg("保存成功");
    // 		}else{
    // 			Msg.showErrorMsg(data.Error);
    // 		}
    // 		that.cancel();
    // 		that.cancelDialog();
    // 		//that.search();
    // 	})
    // },
    getSapInfoBySupplierCode(selSupplierCode, msg) {
      //根据供应商编号获取sap应付人员和采购组织信息
      var obj = {
        name: selSupplierCode
      };
      var that = this;
      _Api.getRalSAPInfoBySupplierCode(obj).then(function(response) {
        var data = response.data;
        if (data.code == "1") {
          msg.supplierCode = that.selSupplierCode;
          msg.supplierName = that.selSupplierName;
          msg.categoryCode = that.selCategoryCode2;
          msg.creatorId = that.$global.user.id;
          msg.creator = that.$global.user.loginName;
          msg.l_SAPCompany = data.rows.l_SAPCompany;
          msg.l_SAPOrg = data.rows.l_SAPOrg;
          _Api.addSupplierInfo(msg).then(function(response) {
            var data = response.data;
            if (data.code == "1") {
              Msg.showSuccessMsg("保存成功");
            } else {
              Msg.showErrorMsg(data.Error);
            }
            that.cancel();
            that.cancelDialog();
            that.search();
          });
        }
      });
    }
  },
  mounted() {
    this.search();
    this.getBtnAuth();
  },
  components: {
    sapSupplierInfo,
    srmCompanyInfo,
    baseInfo,
    supplierSapInfo
  },
  watch: {
    selCategoryCode(value) {
      this.current = 1;
      this.currentPage = 1;
      this.search();
    },
    name(value) {
      this.current = 1;
    }
  }
};
</script>
